package com.audiocn.Utils;

import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;

import com.audiocn.poster.Configs;

public class ConnServerHelper {

	private static final int time_out = 5 * 1000;
	
	public static boolean checkUser() {
		String urlString = Configs.SERVER_URL + "/tlcy/searchABmonth.do?"+Configs.clientTypeANDversion;
		Log.e("checkUser", urlString);
		String rString = getServerString(urlString);
		Log.e("checkUser", rString);
		return true;
	}
	
	/**
	 * 根据URL获取服务器的返回字符串
	 * 
	 * @author wang wei
	 */
	public static String getServerString(String aurl) {
		String rsString = "";
		URL url = weaveUrl(aurl);
		if (url == null) {
			return rsString;
		}
		try {
			String proxyHost = android.net.Proxy.getDefaultHost();
			HttpURLConnection cn = null;
			if (Utils.isWifi()) {
				cn = (HttpURLConnection) url.openConnection();
			} else {
				if (proxyHost != null) {
					java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(android.net.Proxy.getDefaultHost(), android.net.Proxy.getDefaultPort()));
					cn = (HttpURLConnection) url.openConnection(p);
				} else {
					cn = (HttpURLConnection) url.openConnection();
				}
			}
			cn.setRequestProperty("Accept", "*/*");
			cn.setRequestProperty("Accept-Language", "zh-cn");
			cn.setRequestProperty("Accept-Encoding", "");
			cn.setConnectTimeout(time_out);
			cn.setAllowUserInteraction(false);
			cn.setDoInput(true);
			cn.setDoOutput(true);
			cn.setReadTimeout(time_out);
			cn.connect();
			if (cn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				Configs.isCheck = true;
			}
			rsString = new String(Utils.getInputData(cn.getInputStream()), "utf8");
			rsString = rsString.replaceAll("\\r", " ");
			rsString = rsString.replaceAll("\\\\r", " ");
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			rsString = null;
		}
		
		return rsString;
	}
	
	/**
	 * 生成URL
	 * */
	public static URL weaveUrl(String aUrl) {
		URL requestUrl = null;
		try {
			aUrl = aUrl.replaceAll(" ", "");
			if (aUrl.startsWith("http://")) {
				aUrl = aUrl.substring(7);
			}
			requestUrl = new URL("http://" + aUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return requestUrl;
	}
}
